﻿using AutoMapper;
using B.S.BaseData.Api.Write.Application.Command.Eliminates;
using B.S.BaseData.Domain;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;
using MediatR;
using SmartTracking.Domain.ZXL;

namespace B.S.BaseData.Api.Write.Application.CommandHandler.Eliminates
{
    public class CreateEliminateCommandHandler : IRequestHandler<CreateEliminateCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Eliminate> _eliminateRepository;
        private readonly IBaseRepository<Eliminatehead> heads;
        private readonly IMapper map;

        public CreateEliminateCommandHandler(IBaseRepository<Eliminate> eliminateRepository, IMapper map, IBaseRepository<Eliminatehead> heads)
        {
            _eliminateRepository = eliminateRepository;
            this.heads = heads;
            this.map = map;
        }

        public async Task<ApiResult<int>> Handle(CreateEliminateCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();

            try
            {
                if (request.EliminatesList != null && request.EliminatesList.Count > 0)
                {
                    Eliminatehead head = new Eliminatehead();

                    head.EliminationDate = request.EliminationDate;
                    head.SheepType = request.SheepType;
                    head.Documentnumber = request.Documentnumber;

                    await heads.AddAsync(head);

                    int r = await _eliminateRepository.AddRangeAsync(request.EliminatesList);

                    if (r == 0)
                    {
                        res.Message = "创建淘汰失败";
                        res.Code = ApiEnum.新增失败;
                    }
                    else
                    {
                        res.Message = "创建淘汰成功";
                        res.Code = ApiEnum.新增成功;
                    }
                }
                else
                {
                    res.Message = "淘汰列表不能为空";
                    res.Code = ApiEnum.新增失败;
                }
            }
            catch (Exception ex)
            {
                res.Message = "创建失败: " + ex.Message;
                res.Code = ApiEnum.新增失败;
            }

            return res;
        }
    }
}
